<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row :gutter="10">
        <el-button type="primary" @click="addrolesVisible=true">添加角色</el-button>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border>
        <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :gutter="10" 
              v-for="(item,index) in scope.row.children" 
              :key="item.id"
              :class="['bdbottom',index===0?'bdtop':'']"
              class="vcenter"
              >
                <!-- 一级权限 -->
                <el-col :span="5">
                  <el-tag  closable  @close="removerightbyid(scope.row.id,item.id,)">{{item.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二三级权限 -->
                <el-col :span="19">
                  <el-row
                    class="vcenter"
                   :gutter="10" v-for="(item1,index1) in item.children" :key="item1.id">
                    <el-col :span="6" :class="[index1===0 ?'':'bdtop']">
                      <el-tag type="success" closable @close="removerightbyid(scope.row.id,item1.id,)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>

                    </el-col>
                    <el-col :span="18">
                      <el-tag type="warning" 
                      closable
                      v-for="(item2,index2) in item1.children" 
                      :key="item2.id"
                      @close="removerightbyid(scope.row.id,item2.id,)"
                      >
                      {{item2.authName}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope" >
            <el-button type="primary" icon="el-icon-edit" size="mini" 
            @click="showEditRoles(scope.row.id)">编辑</el-button></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" 
            @click="removerolesopen(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" 
            @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="添加角色"
        :visible.sync="addrolesVisible"
        @close="addrolesClosed"
        width="50%"
      >
        <!-- 内容主体 -->
        <el-form
          :model="addrolesForm"
          :rules="addrolesRules"
          ref="addrolesRef"
          label-width="90px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addrolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addrolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addrolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="addrolesclick">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="修改角色"
        :visible.sync="editrolesVisible"
        @close="rolesClosed"
        width="50%"
      >
        <!-- 内容主体 -->
        <el-form
          :model="editrolesForm"
          :rules="rolesRules"
          ref="rolesRef"
          label-width="90px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editrolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editrolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editrolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="editroles">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
  title="分配权限"
  :visible.sync="showSetRightdialogVisible"
  width="50%"
  @close="showSetRightdialogClose"
  >
  <!-- 树形控件 -->
  <el-tree :data="rolelistForm" 
  :props="treeProps" 
  show-checkbox accordion node-key='id' 
  :default-expand-all=true 
  :default-checked-keys="defkeys"
  ref="treeRef"
  ></el-tree>
  <span slot="footer" >
    <el-button @click="showSetRightdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有角色列表
      rolelist: [],
      editrolesForm: {},
      rolelistForm: [],
      addrolesVisible: false,
      editrolesVisible: false,
      showSetRightdialogVisible: false,
      addrolesForm: {},
      roleId: "",
      addrolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      rolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      //树形控件绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      //默认选中的节点
      defkeys: [],
    };
  },
  methods: {
    async getRolelist() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        usersinfo.mg_state = !usersinfo.mg_state;
        return this.$message.error("获取角色列表失败");
      }
      this.rolelist = res.data;
    },
    addrolesClosed() {
      this.$refs.addrolesRef.resetFields();
    },
    rolesClosed() {
      this.$refs.rolesRef.resetFields();
    },
    addrolesclick() {
      this.$refs.addrolesRef.validate(async (value) => {
        if (!value) {
          return;
        }
        const { data: res } = await this.$http.post("roles", this.addrolesForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加角色失败");
          this.addrolesVisible = false;
          return;
        }
        this.$message.success("添加角色成功");
        this.addrolesVisible = false;
        this.getRolelist();
      });
    },
    removerolesopen(id) {
      this.$MessageBox("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("roles/" + id);
          if (res.meta.status !== 200) {
            this.$message.error("删除角色失败");
            return;
          }
          this.getRolelist();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async showEditRoles(id) {
      this.editrolesVisible = true;
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        this.$message.error("查询用户失败");
      }
      this.editrolesForm = res.data;
    },
    editroles() {
      this.$refs.rolesRef.validate(async (value) => {
        if (!value) {
          return;
        }
        const { data: res } = await this.$http.put(
          "roles/" + this.editrolesForm.roleId,
          {
            roleName: this.editrolesForm.roleName,
            roleDesc: this.editrolesForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          this.$message.error("修改角色失败");
          this.editrolesVisible = false;
          return;
        }
        this.$message.success("修改角色成功");
        this.editrolesVisible = false;
        this.getRolelist();
      });
    },
    //根据id删除对应权限
    removerightbyid(roleId, rightId) {
      this.$MessageBox("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${roleId}/rights/${rightId}`
          );
          console.log(res);
          console.log(roleId);
          if (res.meta.status !== 200) {
            this.$message.error("删除角色失败");
            return;
          }
          this.getRolelist();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //分配权限
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        this.$message.error("获取权限失败");
        return;
      }
      // console.log(res);
      this.$message.success("获取权限成功");
      this.rolelistForm = res.data;
      this.getLeafkeys(role, this.defkeys);
      this.showSetRightdialogVisible = true;
    },
    //通过递归的方式获取角色下所有三级权限的id值，并赋值给defkeys
    getLeafkeys(node, arr) {
      //如果当前node节点不包括children属性，就是3级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafkeys(item, arr);
      });
    },
    //监听分配权限对话框关闭
    showSetRightdialogClose() {
      this.defkeys = [];
    },

    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      console.log(idStr);

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败!");
      }
      this.$message.success("分配权限成功!");
      this.getRolelist();
      this.showSetRightdialogVisible = false;
    },
  },
  created() {
    this.getRolelist();
  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>